//
//  TotalServerSynClass.m
//  A One POS
//
//  Created by AonePOS on 24/09/13.
//  Copyright (c) 2013 AonePOS. All rights reserved.
//

#import "TotalServerSynClass.h"
#import "DataBaseManager.h"

@implementation TotalServerSynClass
{
    
  general_data *generalDataObject;
    
}
NSURLConnection *BckupConnection,*PendimgConnection,*InvConnection;
NSMutableData *BackupResponseData,*PendingResponseData,*InvResponseData;

int actualcount;

-(void)ServerSyncronizationMethod
{
     generalDataObject=[general_data new];
    [generalDataObject GetuserDataVariablesMethod];
    NSString *localSystemTime,*PreviousServerSynTime;
    NSString *querySQL = [NSString stringWithFormat: @"SELECT last_server_update_time FROM miscellaneous"];
    NSMutableArray *misArray=[[NSMutableArray alloc]init];
    [[DataBaseManager dataBaseManager]execute:querySQL resultsArray:misArray];
    //[self PendingClearMethod];
    
    if ([misArray count]>0)
    {
        NSString *lasttime;
        for (NSDictionary *Dict in misArray)
        {
            lasttime=[Dict objectForKey:@"last_server_update_time"];
            
        }
        if ([lasttime length]>0)
        {
            PreviousServerSynTime=lasttime;
        }
        else
        {
            PreviousServerSynTime=@"previousday";
            
        }
    }
    localSystemTime=[generalDataObject Datestring];
    
    //NSLog(@"server time %@",PreviousServerSynTime);
    //NSLog(@"local time%@",localSystemTime);
    
    if ([PreviousServerSynTime isEqualToString:@"previousday"])
    {
        if ([[generalDataObject OriginalbaseURLstr] length]>0)
        {
        [self PendingClearMethod];
        
        NSString *string=[NSString stringWithFormat:@"%@backup.php?Currentsystemtime=%@&sessionid=%@&previousday=true",[[generalDataObject OriginalbaseURLstr]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject Datestring] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject SessionID]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
        
        [self BackUpDataMethod:string];
        }
    }
    else
    {
//        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
//        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//        NSDate *date1 = [dateFormat dateFromString:localSystemTime];
//        NSDate *date2=[dateFormat dateFromString:PreviousServerSynTime];
        
        //NSLog(@"date1%@,Date2 %@",date1,date2);
        
        
        //NSTimeInterval diff = [date1 timeIntervalSinceDate:date2];
        
        
        //NSLog(@" time difference %f",diff);
      
            
            if ([[generalDataObject OriginalbaseURLstr] length]>0)
            {
            [self PendingClearMethod];
            
            
            NSString *string=[NSString stringWithFormat:@"%@backup.php?Currentsystemtime=%@&sessionid=%@&previousday=false",[[generalDataObject OriginalbaseURLstr]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject Datestring] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject genRandStringLength:20]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            
            [self BackUpDataMethod:string];
            }
            
            
            
        
    }
    
}
-(void)BackUpDataMethod:(NSString *)str
{
   
    //[self.view addSubview:SynprogressView];
    NSMutableArray *DatabasetablesArray=[[NSMutableArray alloc] initWithObjects:@"department_details",@"category_details",@"vendor",@"inventorytable",@"optional_info_table",@"ordering_info_table",@"alternate_sku",@"modifier_table",@"customer_table",@"customer_general_info_table",@"customer_extended_info_table",@"customer_shipping_table",@"customer_stores_table",@"employee_permissions",@"employee_payroll",@"employee_personal",@"employee_table",@"store_details",@"employee_store",@"invoice_items_table",@"invoice_total_table",@"admin_details",@"split_invoice_table",@"merchant_info_table",@"mercury_pay_table",@"paymentprocessorpreferencess",@"login_logout_table", nil];
    
    NSMutableArray *deleteArray=[[NSMutableArray alloc]init];
    
    for (int i=0; i<[DatabasetablesArray count]; i++)
    {
        NSString *selectedTable=[DatabasetablesArray objectAtIndex:i];
        NSString *deletesql=[NSString stringWithFormat:@"DELETE FROM %@",selectedTable];
        [[DataBaseManager dataBaseManager]executeRecordsWithQuery:deletesql withArguments:deleteArray];
        
    }
    
    //NSLog(@"%@",str);
    
    NSURL *url=[NSURL URLWithString:str];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    //NSLog(@"%@",url);
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    
    BckupConnection = [[NSURLConnection alloc]
                       initWithRequest:request
                       delegate:self startImmediately:NO];
    
    [BckupConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                               forMode:NSDefaultRunLoopMode];
    
    [BckupConnection start];
    
    
}
-(void)PendingClearMethod
{
    
    NSMutableArray  *QuerytypesArray=[[NSMutableArray alloc]init];
    NSMutableArray  *TablenamesArray=[[NSMutableArray alloc]init];
    NSMutableArray  *FieldsArray=[[NSMutableArray alloc]init];
    
    int offset=0;
    
    
    NSString *String;
    
    NSString *selectsql2=[NSString stringWithFormat:@"SELECT   query_type,table_name,parameters FROM pending_queries  where user_id='%@' ORDER BY current_time='%@' ASC ",[generalDataObject userID],[generalDataObject Datestring]];
    //NSLog(@"pending query %@",selectsql2);
    NSMutableArray *pendingsArray=[[NSMutableArray alloc]init];
    [[DataBaseManager dataBaseManager]execute:selectsql2 resultsArray:pendingsArray];
    
    int count=[pendingsArray count];
    
    for (;offset<count; )
    {
        
        NSString *selectsql=[NSString stringWithFormat:@"SELECT  query_type,table_name,parameters FROM pending_queries  where user_id='%@' ORDER BY current_time='%@' ASC limit 100 offset %d",[generalDataObject userID],[generalDataObject Datestring],offset];
        
        NSMutableArray *pendingsArray=[[NSMutableArray alloc]init];
        
        
        if(count<100)
        {
			offset = offset+count;
		}
        else
        {
			offset = offset+100;
			count = count - offset;
		}
        
        if ([selectsql length]>0)
        {
            [[DataBaseManager dataBaseManager]execute:selectsql2 resultsArray:pendingsArray];
        }
        
        
        if ([pendingsArray count]>0)
        {
            
            for (NSDictionary *Dict in pendingsArray)
            {
                [QuerytypesArray addObject:[Dict objectForKey:@"query_type"]];
                [TablenamesArray addObject:[Dict objectForKey:@"table_name"]];
                [FieldsArray addObject:[Dict objectForKey:@"parameters"]];
                
            }
            for (int i=0; i<[QuerytypesArray count]; i++)
            {
                NSString *Querytype=[QuerytypesArray objectAtIndex:i];
                NSString *tablename=[TablenamesArray objectAtIndex:i];
                NSString *parameters=[FieldsArray objectAtIndex:i];
                if ([Querytype isEqualToString:@"createadminprofile"])
                {
                    String=[NSString stringWithFormat:@"%@create-admin-profile.php?defaultusername=01&defaultpassword=admin&data=%@",[generalDataObject OriginalbaseURLstr],[parameters stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                    
                    NSURL *url=[NSURL URLWithString:String];
                    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
                    //NSLog(@"%@",url);
                    
                    [request setHTTPMethod:@"POST"];
                    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                    //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                    
                    
                    
                    PendimgConnection = [[NSURLConnection alloc]
                                         initWithRequest:request
                                         delegate:self startImmediately:NO];
                    
                    [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                                 forMode:NSDefaultRunLoopMode];
                    [PendimgConnection start];
                    
                }
                if ([Querytype isEqualToString:@"login"])
                {
                    
                    String=[NSString stringWithFormat:@"%@user-login.php?%@",[generalDataObject OriginalbaseURLstr],parameters];
                    NSURL *url=[NSURL URLWithString:String];
                    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
                    // //NSLog(@"%@",url);
                    
                    [request setHTTPMethod:@"POST"];
                    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                    //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                    
                    
                    
                    PendimgConnection = [[NSURLConnection alloc]
                                         initWithRequest:request
                                         delegate:self startImmediately:NO];
                    
                    [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                                 forMode:NSDefaultRunLoopMode];
                    [PendimgConnection start];
                    
                    
                }
                if ([Querytype isEqualToString:@"logout"])
                {
                    String=[NSString stringWithFormat:@"%@user-login.php?%@",[generalDataObject OriginalbaseURLstr],parameters];
                    NSURL *url=[NSURL URLWithString:String];
                    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
                    ////NSLog(@"%@",url);
                    
                    [request setHTTPMethod:@"POST"];
                    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                    //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                    
                    
                    
                    PendimgConnection = [[NSURLConnection alloc]
                                         initWithRequest:request
                                         delegate:self startImmediately:NO];
                    
                    [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                                 forMode:NSDefaultRunLoopMode];
                    [PendimgConnection start];
                    
                }
                if ([Querytype isEqualToString:@"INSERT"])
                {
                    
                    String=[NSString stringWithFormat:@"%@saveinfo.php?tablename=%@&systemtime=%@&userid=%@&sessionid=%@&data=%@",[generalDataObject OriginalbaseURLstr],[tablename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject Datestring] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[generalDataObject userID],[generalDataObject genRandStringLength:20],[parameters stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                    
                    NSURL *url=[NSURL URLWithString:String];
                    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
                    // //NSLog(@"%@",url);
                    
                    [request setHTTPMethod:@"POST"];
                    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                    //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                    
                    
                    
                    PendimgConnection = [[NSURLConnection alloc]
                                         initWithRequest:request
                                         delegate:self startImmediately:NO];
                    
                    [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                                 forMode:NSDefaultRunLoopMode];
                    [PendimgConnection start];
                    
                }
                if ([Querytype isEqualToString:@"UPDATE"])
                {
                    
                    String=[NSString stringWithFormat:@"%@saveinfo.php?tablename=%@&systemtime=%@&userid=%@&sessionid=%@&data=%@&update=true",[generalDataObject OriginalbaseURLstr],[tablename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject Datestring] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[generalDataObject userID],[generalDataObject genRandStringLength:20],[parameters stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                    NSURL *url=[NSURL URLWithString:String];
                    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
                    // //NSLog(@"%@",url);
                    
                    [request setHTTPMethod:@"POST"];
                    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                    //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                    
                    
                    
                    PendimgConnection = [[NSURLConnection alloc]
                                         initWithRequest:request
                                         delegate:self startImmediately:NO];
                    
                    [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                                 forMode:NSDefaultRunLoopMode];
                    [PendimgConnection start];
                    
                }
                if ([Querytype isEqualToString:@"DELETE"])
                {
                    String=[NSString stringWithFormat:@"%@deleteinfo.php?tablename=%@&systemtime=%@&userid=%@&sessionid=%@&unique_ids=%@",[generalDataObject OriginalbaseURLstr],[tablename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject Datestring] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[generalDataObject userID],[generalDataObject genRandStringLength:20],[parameters stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                    NSURL *url=[NSURL URLWithString:String];
                    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
                    ////NSLog(@"%@",url);
                    
                    [request setHTTPMethod:@"POST"];
                    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                    //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                    
                    PendimgConnection = [[NSURLConnection alloc]
                                         initWithRequest:request
                                         delegate:self startImmediately:NO];
                    
                    [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                                 forMode:NSDefaultRunLoopMode];
                    [PendimgConnection start];
                    
                }
                if ([Querytype isEqualToString:@"edit"])
                {
                    
                    NSString   *bodyString  = [NSString stringWithFormat:@"query-string=%@",[parameters stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                    
                    NSString *urlstring=[NSString stringWithFormat:@"%@execute.php?",[generalDataObject OriginalbaseURLstr]];
                    
                    /////NSLog(@"%@",bodyString);
                    // //NSLog(@"%@",urlstring);
                    
                    NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstring]];
                    
                    [request setTimeoutInterval:20.0];
                    
                    NSData *requestData = [NSData dataWithBytes:[bodyString UTF8String] length:[bodyString length]];
                    
                    [request setHTTPMethod:@"POST"];
                    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
                    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                    
                    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                    [request setValue:[NSString stringWithFormat:@"%d", [bodyString length]] forHTTPHeaderField:@"Content-Length"];
                    [request setHTTPBody:requestData];
                    ////NSLog(@"%@",request);
                    
                    InvConnection = [NSURLConnection connectionWithRequest:request delegate:self];
                    
                    [InvConnection start];
                    
                }
                
            }
        }
    }
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    
    if (connection == BckupConnection){
        BackupResponseData = [[NSMutableData alloc] init];
    }else if (connection == PendimgConnection){
        PendingResponseData = [[NSMutableData alloc] init];
    }else if (connection==InvConnection){
        InvResponseData = [[NSMutableData alloc] init];
    }
    
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    if (connection == BckupConnection){
        [BackupResponseData appendData:data];
    }else if (connection == PendimgConnection){
        [PendingResponseData appendData:data];
    }else if (connection==InvConnection){
        [InvResponseData appendData:data];
    }

    
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    if (connection==InvConnection){
        NSString *responseStr = [[NSString alloc] initWithBytes:[InvResponseData mutableBytes] length:[InvResponseData length] encoding:NSUTF8StringEncoding];
        //NSLog(@"%@",responseStr);
        NSError *error;
        NSMutableDictionary *dataDict;
      dataDict=[[NSMutableDictionary alloc] init];
        NSData *jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
        dataDict =[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        //NSLog(@"repose  data %@",dataDict);
        
        
        NSString *Servertime=[[dataDict objectForKey:@"response"] objectForKey:@"server-time"];
        //NSLog(@"%@",Servertime);
        NSString *selectQuery=[NSString stringWithFormat:@"select selected_store, local_time,pageurl,last_server_update_time from miscellaneous"];
        NSMutableArray *mislaneousArray=[[NSMutableArray alloc]init];
        [[DataBaseManager dataBaseManager]execute:selectQuery resultsArray:mislaneousArray];
        
        if ([mislaneousArray count]>0){
            NSString *updateSQL =@"UPDATE miscellaneous SET last_server_update_time=?";
            NSMutableArray *misUpdatearray=[[NSMutableArray alloc]initWithObjects:Servertime, nil];
            [[DataBaseManager dataBaseManager] executeRecordsWithQuery:updateSQL withArguments:misUpdatearray];
        }else{
            NSString *insertSQL =@"insert into miscellaneous (selected_store,local_time,pageurl,last_server_update_time) values(?,?,?,?)";
            NSMutableArray *misUpdatearray=[[NSMutableArray alloc]initWithObjects:@"Store1",[generalDataObject Datestring],[generalDataObject OriginalbaseURLstr],Servertime, nil];
            [[DataBaseManager dataBaseManager]executeRecordsWithQuery:insertSQL withArguments:misUpdatearray];
        }
        
    }else if (connection == BckupConnection){
        
        NSString *responseStr = [[NSString alloc] initWithBytes:[BackupResponseData mutableBytes] length:[BackupResponseData length] encoding:NSUTF8StringEncoding];
        
        NSError *error;
        
        NSMutableDictionary *dataDict;
        dataDict=[[NSMutableDictionary alloc] init];
        NSData *jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
        dataDict =[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        //NSLog(@"back up data %@",dataDict);
        
        NSMutableArray *deleteArray=[dataDict objectForKey:@"queries-array"];
        // NSMutableArray *insertsArray=[dataDict objectForKey:@"insert-queries"];
        
        NSMutableArray *deletesArray=[[NSMutableArray alloc]init];
        for (int i=0; i<[deleteArray count]; i++)
        {
            NSString *foo=[deleteArray objectAtIndex:i];
            NSString* bar = [foo stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
            NSString* deletestr = [bar stringByReplacingOccurrencesOfString:@"\\\"" withString:@"'"];
            [[DataBaseManager dataBaseManager]executeRecordsWithQuery:deletestr withArguments:deletesArray];
            
        }
        NSString *nexturl=[dataDict objectForKey:@"next-url"];
        if([nexturl isKindOfClass:[NSNull class]])
        {
            //NSLog(@"next url null");
        }
        else
        {
            [self BackUpDataMethod:nexturl];
            
        }
        NSString *actualrowcount=[dataDict objectForKey:@"actual-row-count"];
        actualcount=[actualrowcount intValue];
        
        NSString *selectQuery=[NSString stringWithFormat:@"select selected_store, local_time,pageurl,last_server_update_time from miscellaneous"];
        NSMutableArray *mislaneousArray=[[NSMutableArray alloc]init];
        [[DataBaseManager dataBaseManager]execute:selectQuery resultsArray:mislaneousArray];
        
        if ([mislaneousArray count]>0){
            NSString *updateSQL =@"UPDATE miscellaneous SET last_server_update_time=?";
            NSMutableArray *misUpdatearray=[[NSMutableArray alloc]initWithObjects:[generalDataObject getsystemDatetime], nil];
            [[DataBaseManager dataBaseManager] executeRecordsWithQuery:updateSQL withArguments:misUpdatearray];
            
        }else{
            NSString *insertSQL =@"insert into miscellaneous (selected_store,local_time,pageurl,last_server_update_time) values(?,?,?,?)";
            NSMutableArray *misUpdatearray=[[NSMutableArray alloc]initWithObjects:@"Store1",[generalDataObject getsystemDatetime],[generalDataObject OriginalbaseURLstr],[generalDataObject getsystemDatetime], nil];
            [[DataBaseManager dataBaseManager]executeRecordsWithQuery:insertSQL withArguments:misUpdatearray];
        }
        
    }else if (connection == PendimgConnection){
        
        NSString *responseStr = [[NSString alloc] initWithBytes:[PendingResponseData mutableBytes] length:[PendingResponseData length] encoding:NSUTF8StringEncoding];
        
        NSError *error;
        NSMutableDictionary *dataDict;
      dataDict=[[NSMutableDictionary alloc] init];
        NSData *jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
        dataDict =[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        //NSLog(@"Pending query data %@",dataDict);
        
        NSMutableArray *deleteArray=[dataDict objectForKey:@"delete-queries"];
        NSMutableArray *insertsArray=[dataDict objectForKey:@"insert-queries"];
        
        NSMutableArray *deletesArray;
        for (int i=0; i<[deleteArray count]; i++)
        {
            NSString *foo=[deleteArray objectAtIndex:i];
            NSString* bar = [foo stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
            NSString* deletestr = [bar stringByReplacingOccurrencesOfString:@"\\\"" withString:@"'"];
            [[DataBaseManager dataBaseManager]executeRecordsWithQuery:deletestr withArguments:deletesArray];
            
            NSString *foo2=[insertsArray objectAtIndex:i];
            NSString* bar2 = [foo2 stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
            NSString* insertstr = [bar2 stringByReplacingOccurrencesOfString:@"\\\"" withString:@"'"];
            
            [[DataBaseManager dataBaseManager]executeRecordsWithQuery:insertstr withArguments:deletesArray];
        }
        
        NSString *Deletependingquery=[NSString stringWithFormat:@"DELETE FROM pending_queries "];
        [[DataBaseManager dataBaseManager]executeRecordsWithQuery:Deletependingquery withArguments:deletesArray];
        
    }
}

@end
